@extends('admin.base')

@section('content')
    <div class="layui-card">
        <div class="layui-card-header layuiadmin-card-header-auto">
            <h2>添加商品</h2>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" action="{{route('admin.goods.store')}}" method="post">

                <div class="layuimini-container">
                    <div class="layui-form-item">
                        <label class="layui-form-label">规格名</label>
                        <div class="layui-input-block" id="specItem">
                            @foreach($specs as $vo)
                                <input type="checkbox" lay-filter="specs"  class="specs{{$vo["id"]}}" name="specs[]" data-title="{{$vo["title"]}}" title="{{$vo["title"]}}" value="{{$vo["id"]}}" content="{{$vo["content"]}}" data-id="{{$vo["id"]}}">
                            @endforeach
                        </div>
                    </div>
                    <form action="" class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">规格：</label>
                            <div class="layui-input-block">
                                <table class="layui-table" id="spec-table">
                                    <thead>
                                    <tr>
                                        <th>规格名</th>
                                        <th>规格值</th>
                                    </tr>
                                    </thead>
                                    <tbody>

                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="layui-form-item layui-hide">
                            <label class="layui-form-label">批量设置：</label>
                            <div class="layui-input-block">
                                <table class="layui-table" id="sku-price"  lay-filter="sku-price">
                                    <thead>
                                    </thead>
                                    <tbody></tbody>
                                </table>
                            </div>
                        </div>
                        <div class="layui-form-item layui-hide">
                            <label class="layui-form-label">SKU表：</label>
                            <div class="layui-input-block">
                                <table class="layui-table" id="sku-table">
                                    <thead></thead>
                                    <tbody></tbody>
                                </table>
                            </div>
                        </div>

                    </form>
                </div>

            </form>
        </div>
    </div>
    <script>

        layui.use(['form', 'upload', 'jquery','table'], function() {
            var form = layui.form,
                upload = layui.upload,
                $ = layui.jquery;
            var table = layui.table;

            function createSkuTable(url = '/admin/ajax/upload') {
                var specData = [];
                $.each($('#spec-table tbody tr'), function() {
                    var child = [];
                    $.each($(this).find('input[type=checkbox]'), function() {
                        child.push({ id: $(this).val(), title: $(this).attr('title'), checked: $(this).is(':checked') });
                    });
                    var specItem = { id: $(this).find('td').eq(0).attr('data-id'), title: $(this).find('td').eq(0).text(), show: $(this).find('input[type=checkbox]:checked').length > 0, child: child };

                    specData.push(specItem);
                });
                // console.log(specData)
                if ($('#spec-table tbody input[type=checkbox]:checked').length) {
                    $('#sku-table').parent().parent().removeClass('layui-hide');
                    $('#sku-price').parent().parent().removeClass('layui-hide');
                    var prependThead = [],
                        prependTbody = [];
                    $.each(specData, function() {
                        if (this.show) {
                            prependThead.push(this.title);
                            var prependTbodyItem = [];
                            $.each(this.child, function() {
                                if (this.checked) {
                                    prependTbodyItem.push({ id: this.id, title: this.title });
                                }
                            });
                            prependTbody.push(prependTbodyItem);
                        }
                    });
                    if (prependThead.length > 0) {
                        $('#sku-table thead').html('<tr>' +
                            prependThead.map(function(t, i, a) {
                                return '<th>' + t + '</th>'
                            }) +
                            '<th>图片</th>' +
                            '<th>门店价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>会员价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>特殊价(元) <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>库存 <i class="layui-icon layui-icon-cols"></i></th>' +
                            '<th>门店价是否显示 </th>' +
                            '<th>会员价是否显示 </th>' +
                            '<th>特殊价是否显示 </th>' +
                            '<th>状态 </th>' +
                            '</tr>');
                        $('#sku-price thead').html('<tr><th>图片</th>' +
                            '<th>门店价(元)</th>' +
                            '<th>会员价(元)</th>' +
                            '<th>特殊价(元)</th>' +
                            '<th>库存 </th>' +
                            '<th>门店价是否显示 </th>' +
                            '<th>会员价是否显示 </th>' +
                            '<th>特殊价是否显示 </th>' +
                            // '<th>状态 </th>' +
                            '<th>操作 </th>' +
                            '</tr>');
                    }

                    var prependTbodyTrs = [];
                    var prependTbodyTrsPrice = [];
                    // console.log(prependTbody)
                    prependTbody.reduce(function(prev, cur, index, array) {
                        var tmp = [];
                        prev.forEach(function(a) {
                            cur.forEach(function(b) {
                                tmp.push({ id: a.id + ',' + b.id, title: a.title + ',' + b.title });
                            })
                        });
                        return tmp;
                    }).forEach(function(item, index, array) {
                        // console.log(item)
                        var  attrCate="";
                        var  attrCateMember="";
                        var  attrCateActivity="";
                        attrCate+='<input type="text" name="skus[' + item.id + '][price]" value="0" id="price'+index+'" class="layui-input" lay-verify="required|number" lay-reqtext="门店价不能为空">'
                        attrCateMember+='<input type="text" name="skus[' + item.id + '][member_price]" id="member_price'+index+'" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="会员价不能为空">'
                        attrCateActivity+='<input type="text" name="skus[' + item.id + '][activity_price]" id="activity_price'+index+'" value="0" class="layui-input" lay-verify="required|number" lay-reqtext="特殊价不能为空">'


                        prependTbodyTrs.push('<tr>' +
                            item.title.split(',').map(function(t, i, a) {
                                return '<td>' + t + '</td>';
                            }) +
                            '<td><input type="hidden" name="skus[' + item.id + '][picture]" value=""><img src="__STATIC__/admin/images/sku-add.png" alt="sku图片"></td>' +
                            '<td>'+attrCate+'</td>' +
                            '<td>'+attrCateMember+'</td>' +
                            '<td>'+attrCateActivity+'</td>' +
                            '<td><input type="text" name="skus[' + item.id + '][stock]" value="99999" class="layui-input stock" id="stock'+index+'" lay-verify="required|number" lay-reqtext="库存不能为空"></td>' +
                            '<td><div class="layui-input-inline"> <input type="checkbox" name="skus[' + item.id + '][price_show]" id="price_show'+index+'" lay-skin="switch" lay-text="是|否" checked></div></td>' +
                            '<td><div class="layui-input-inline"><input type="checkbox" name="skus[' + item.id + '][member_show]" id="member_show'+index+'" lay-skin="switch" lay-text="是|否" checked></div></td>' +
                            '<td><div class="layui-input-inline"><input type="checkbox" name="skus[' + item.id + '][activity_show]" id="activity_show'+index+'" lay-skin="switch" lay-text="是|否" ></div></td>' +
                            '<td><select name="skus[' + item.id + '][status]"><option value="1">启用</option><option value="0">禁用</option></select></td>' +
                            '</tr>');
                    });
                    attrCate="";
                    attrCateMember="";
                    attrCateActivity="";

                    attrCate+='<input type="text" " value="0" class="layui-input"  lay-verify="required|number" lay-reqtext="门店价不能为空">'
                    attrCateMember+='<input type="text"  value="0"  class="layui-input" lay-verify="required|number" lay-reqtext="会员价不能为空">'
                    attrCateActivity+='<input type="text"  value="0"  class="layui-input" lay-verify="required|number" lay-reqtext="特殊价不能为空">'

                    prependTbodyTrsPrice.push('<tr ><td><input type="hidden"  value=""><img src="__STATIC__/admin/images/sku-add.png" alt="sku图片"></td>' +
                        '<td>'+attrCate+'</td>' +
                        '<td>'+attrCateMember+'</td>' +
                        '<td>'+attrCateActivity+'</td>' +
                        '<td><input type="text"  value="99999" class="layui-input" lay-verify="required|number" lay-reqtext="库存不能为空"></td>' +
                        '<td><div class="layui-input-inline"><input type="radio" name="price_show" value="1" title="是" checked><input type="radio" name="price_show" value="0" title="否"></div></td>' +
                        '<td><div class="layui-input-inline"><input type="radio" name="member_show" value="1" title="是" checked><input type="radio" name="member_show" value="0" title="否"></div></td>' +
                        '<td><div class="layui-input-inline"><input type="radio" name="activity_show" value="1" title="是" checked><input type="radio" name="activity_show" value="0" title="否"></div></td>' +
                        // '<td><select name="skus[status]"><option value="1">启用</option><option value="0">禁用</option></select></td>' +
                        '<td><a class="layui-btn layui-btn-xs layui-btn-success batchadd" onclick="batchadd()"  data-title="批量添加" >批量添加</a></td>' +
                        '</tr>');
                    if (prependTbodyTrs.length > 0) {
                        $('#sku-table tbody').html(prependTbodyTrs.join(''));
                        $('#sku-price tbody').html(prependTbodyTrsPrice.join(''));
                        $('input[name=spec]').val(JSON.stringify(specData));
                        form.render();
                        upload.render({
                            elem: '#sku-table td img',
                            url: url,
                            exts: 'png|jpg|ico|jpeg|gif',
                            accept: 'images',
                            acceptMime: 'image/*',
                            multiple: false,
                            done: function(res) {
                                if (res.code === 1) {
                                    var url = res.data.url;
                                    // console.log(url)
                                    $(this.item).attr('src', url).prev().val(url);
                                    layer.msg(res.msg);
                                } else {
                                    layer.msg(res.msg);
                                }
                                return false;
                            }
                        });
                        upload.render({
                            elem: '#sku-price td img',
                            url: url,
                            exts: 'png|jpg|ico|jpeg|gif',
                            accept: 'images',
                            acceptMime: 'image/*',
                            multiple: false,
                            done: function(res) {
                                if (res.code === 1) {
                                    var url = res.data.url;
                                    // console.log(this.item)
                                    $(this.item).attr('src', url).prev().val(url);
                                    layer.msg(res.msg);
                                } else {
                                    layer.msg(res.msg);
                                }
                                return false;
                            }
                        });
                    }
                } else {
                    $('#sku-table').parent().parent().addClass('layui-hide');
                    $('#sku-table thead').html('');
                    $('#sku-table tbody').html('');
                    $('#sku-price').parent().parent().addClass('layui-hide');
                    $('#sku-price thead').html('');
                    $('#sku-price tbody').html('');
                    $('input[name=spec]').val('');
                }
            }

            /**
             * 初始化sku表
             */
            createSkuTable();

            /**
             * 监听sku表变化
             */
            form.on('checkbox(filter)', function(data) {

                createSkuTable();
            });

            /**
             * 监听批量赋值
             */
            $(document).on('click', '#sku-table thead tr th i', function() {

                var that = this;
                layer.prompt(function(value, index, elem) {
                    $.each($('#sku-table tbody tr'), function() {
                        if($(that).parent().index()==5){
                            $(this).find('td').eq($(that).parent().index()).children('input').val(value);
                        }else{
                            $(this).find('td').eq($(that).parent().index()).children('div').find('input').val(value);
                        }

                    });
                    layer.close(index);
                });
            });
            /**
             * 监听表单提交
             */
            form.on('submit(submit)', function(data) {
                var state = Object.keys(data.field).some(function(item, index, array) {
                    return item.startsWith('skus');
                });
                state ? layer.alert(JSON.stringify(data.field), { title: '提交的数据' }) : layer.msg('sku表数据不能为空', { icon: 5, anim: 6 });
                return false;
            });

            // 选择规格模板
            form.on('checkbox(specs)', function(data) {
                console.log(data)
                let dataId = $(this).attr('data-id')
                let title = $(this).attr('data-title')

                let hasId = $('#spec-table tbody').find('tr').hasClass('specs'+dataId)
                // console.log(hasId)
                if (hasId) {
                    $('.specs'+dataId).remove()
                    return false
                }
                let content = $(this).attr('content')

                let contentArr = content.split(',')

                let = input = ''
                for(var i in contentArr){
                    input += '<input type="checkbox" title="'+contentArr[i]+'" lay-filter="filter" name="specs_value['+title+'][]" value="'+contentArr[i]+'">'
                }
                $('#spec-table tbody').append('<tr class="specs'+dataId+'"><td>'+title+'</td><td>'+input+'</td></tr>')
                form.render()
                createSkuTable()
            });
            //规格加载
            $('.spec1').click(function () {
                var cate_id=$("#cateId").val();
                var params={
                    cate_id:cate_id
                }
                $.ajax({
                    url:"{:url('platform.spec/getspec')}",
                    dataType: 'json',
                    data : JSON.stringify(params),
                    contentType: "application/json",
                    type: 'post',
                    success: function (data) {
                        var html='';
                        $.each(data.data, function (index, item) {
                            html+='<input type="checkbox" lay-filter="specs"  class="specs'+item.id+'" name="specs[]" data-title="'+item.title+'" title="'+item.title+'" value="'+item.id+'" content="'+item.content+'" data-id="'+item.id+'"><div class="layui-unselect layui-form-checkbox"><span>'+item.title+'</span><i class="layui-icon layui-icon-ok"></i></div>';
                        });

                        // $("#specItem").html('');
                        $("#specItem").append(html);

                    }
                });
            });

        });
        /*
        批量赋值
        */
        function batchadd(){
            var that=this;
            var picture=''
            var stock=0
            var price=[]
            var member_price=[]
            var activity_price=[]
            var price_show=0
            var member_show=0
            var activity_show=0
            //取值
            $.each($('#sku-price tbody tr').find("td"), function(index, value) {

                switch (index) {
                    case 1:
                        price.push($(this).find('input').val())
                        break;
                    case 2:
                        member_price.push($(this).find('input').val())
                        break;
                    case 3:
                        activity_price.push($(this).find('input').val())
                        break;
                    case 0:
                        picture=$(this).children('input').val()
                        break;
                    case 4:
                        stock=$(this).children('input').val()
                        break;
                    case 5:
                        price_show=$(this).children('div').find('input[name="price_show"]:checked').val()
                        break;
                    case 6:
                        member_show=$(this).children('div').find('input[name="member_show"]:checked').val()
                        break;
                    case 7:
                        activity_show=$(this).children('div').find('input[name="activity_show"]:checked').val()
                        break;
                }

                // if($(that).parent().index()==5){
                //     $(this).find('td').eq($(that).parent().index()).children('input').val(value);
                // }else{
                //     $(this).find('td').eq($(that).parent().index()).children('div').find('input').val(value);
                // }

            });

            //赋值
            $.each($('#sku-table tbody tr'), function(index, value) {
                var _this=this;
                $.each($(this).children('td'),function(i,v){
                    if($(this).find('img').length>0){
                        if(picture){
                            $(this).find("input[type=hidden]").val(picture)
                            $(this).find('img').attr('src',picture)
                        }
                    }
                    if($(this).find('#stock'+index).val()){
                        $(this).find('#stock'+index).val(stock)
                    }
                    if($(this).find('#price'+index)){
                        $(this).find('#price'+index).val(price[0])
                    }
                    if($(this).find('#member_price'+index)){
                        $(this).find('#member_price'+index).val(member_price[0])
                    }
                    if($(this).find('#activity_price'+index)){
                        $(this).find('#activity_price'+index).val(activity_price[0])
                    }
                    if($(this).find('#price_show'+index)){
                        if(price_show==1){
                            $(this).children('div').find('input[type="checkbox"]').prop('checked', true);
                        } else{
                            $(this).children('div').find('input[type="checkbox"]').prop('checked', false);
                        }


                    }
                    if($(this).find('#member_show'+index)){
                        if(member_show==1){
                            $(this).children('div').find('input[type="checkbox"]').prop('checked', true);
                        } else{
                            $(this).children('div').find('input[type="checkbox"]').prop('checked', false);
                        }
                    }
                    if($(this).find('#activity_show'+index)){
                        if(activity_show==1){
                            $(this).children('div').find('input[type="checkbox"]').prop('checked', true);
                        } else{
                            $(this).children('div').find('input[type="checkbox"]').prop('checked', false);
                        }

                    }

                });
                form.render('checkbox')

            });

        }
    </script>
@endsection


